package com.sky.service.impl;

import com.sky.entity.Orders;
import com.sky.mapper.ReportMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class ReportServiceImpl implements ReportService {
    @Autowired
    private ReportMapper reportMapper;
    @Autowired
    private WorkspaceService workspaceService;

    @Override
    public SalesTop10ReportVO getSalesTop10(LocalDate begin, LocalDate end) {
        LocalDateTime b = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime e = LocalDateTime.of(end, LocalTime.MAX);
        List<Map<String, Object>> map = reportMapper.getSalesTop10(b, e);
        //这里也可以不用map 用GoodSalesDTO来封装对应的字段name 和 number然后返回的就是他的一个list
        //map里面封装的有两个 一个是name字段对应名字 一个是number字段对应数量
        List<Object> list1 = map.stream().map(m -> m.get("name")).collect(Collectors.toList());
        List<Object> list2 = map.stream().map(m -> m.get("number")).collect(Collectors.toList());
        String nameList = StringUtils.join(list1, ",");
        String numberList = StringUtils.join(list2, ",");
        return new SalesTop10ReportVO(nameList, numberList);
    }

    @Override
    public OrderReportVO getOrderStatistics(LocalDate begin, LocalDate end) {
        //同样需要每一天的日期
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while (!begin.isEqual(end)) {
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        List<Integer> orderCountList = new ArrayList<>();//统计一共的订单数 不需要状态
        List<Integer> orderValidList = new ArrayList<>();//统计有效订单数 状态是5的完成订单
        int totalOrderCount=0;//最后把集合里面的加起来就好了
        int validOrderCount=0;
        //订单完成率等于有效订单除以总订单
        for (LocalDate date : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            Integer orderCount = reportMapper.getOrderCount(beginTime, endTime,null);
            totalOrderCount += orderCount;
            orderCountList.add(orderCount);
            Integer validCount = reportMapper.getOrderCount(beginTime, endTime, Orders.COMPLETED);
            validOrderCount += validCount;
            orderValidList.add(validCount);
        }
        Double orderCompletionRate=(double)validOrderCount/totalOrderCount;
        String dateListString = StringUtils.join(dateList, ",");
        String orderCountListString = StringUtils.join(orderCountList, ",");
        String orderValidListString = StringUtils.join(orderValidList, ",");
        return new OrderReportVO(dateListString, orderCountListString, orderValidListString, totalOrderCount, validOrderCount, orderCompletionRate);
    }

    @Override
    public UserReportVO getUserStatistics(LocalDate begin, LocalDate end) {
        //从begin到end之间的所有日期都要拿到
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while (!begin.isEqual(end)) {
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        List<Integer> newUserList = new ArrayList<>();
        List<Integer> totalUserList = new ArrayList<>();
        //从里面拿日期去找 新建和总用户数
        for (LocalDate date : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            Integer newUserCount = reportMapper.getNewUsers(beginTime, endTime);
            newUserList.add(newUserCount);
            Integer totalUserCount = reportMapper.getNewUsers(null, endTime);
            totalUserList.add(totalUserCount);
        }
        String dateListString = StringUtils.join(dateList, ",");
        String newUserListString = StringUtils.join(newUserList, ",");
        String totalUserListString = StringUtils.join(totalUserList, ",");
        return new UserReportVO(dateListString, totalUserListString, newUserListString);
    }

    @Override
    public TurnoverReportVO getTurnoverStatistics(LocalDate begin, LocalDate end) {
        //一样是需要每一天的数据 营业额就是每天的成交金额 就是商品状态为5的订单查询金额BigDecimal类型的数据
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while (!begin.isEqual(end)) {
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        //接下来要根据dateList内封装的日期去找
        List<BigDecimal> turnoverList = new ArrayList<>();
        for (LocalDate date : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            BigDecimal turnover = reportMapper.getTurnover(beginTime, endTime,Orders.COMPLETED);
            turnoverList.add(turnover);
        }
        String dateListString = StringUtils.join(dateList, ",");
        String turnoverListString = StringUtils.join(turnoverList, ",");
        return new TurnoverReportVO(dateListString, turnoverListString);
    }

    @Override
    public void exportBusinessData(HttpServletResponse response){
        LocalDate beginDate = LocalDate.now().minusDays(30);
        LocalDate endDate = LocalDate.now().minusDays(1);
        //先获取对应的数据 营业额 订单完成率 新增用户数 有效订单数 平均客单价 近30天的数据
        BusinessDataVO businessDataVO = workspaceService.getBusinessData(LocalDateTime.of(beginDate, LocalTime.MIN),LocalDateTime.of(endDate, LocalTime.MAX));
        //获取表格的输入流
        InputStream in = this.getClass().getClassLoader().getResourceAsStream("template/BusinessData.xlsx");
        try {
            XSSFWorkbook excel=new XSSFWorkbook(in);
            XSSFSheet sheet = excel.getSheet("Sheet1");
            sheet.getRow(1).getCell(1).setCellValue("时间"+beginDate.toString()+"到"+endDate.toString());
            sheet.getRow(3).getCell(2).setCellValue(businessDataVO.getTurnover());//营业额
            sheet.getRow(4).getCell(2).setCellValue(businessDataVO.getValidOrderCount());
            sheet.getRow(3).getCell(4).setCellValue(businessDataVO.getOrderCompletionRate());
            sheet.getRow(4).getCell(4).setCellValue(businessDataVO.getUnitPrice());
            sheet.getRow(3).getCell(6).setCellValue(businessDataVO.getNewUsers());
            for(int i=0;i<30;i++){
                //循环为每一行添加
                LocalDate time = beginDate.plusDays(i);
                LocalDateTime begin = LocalDateTime.of(time, LocalTime.MIN);
                LocalDateTime end = LocalDateTime.of(time, LocalTime.MAX);
                BusinessDataVO businessData = workspaceService.getBusinessData(begin,end);
                XSSFRow row = sheet.getRow(7+i);
                //日期 营业额 有效订单数 订单完成率 平均客单价 新增用户数
                row.getCell(1).setCellValue(time.toString());
                row.getCell(2).setCellValue(businessData.getTurnover());
                row.getCell(3).setCellValue(businessData.getValidOrderCount());
                row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
                row.getCell(5).setCellValue(businessData.getUnitPrice());
                row.getCell(6).setCellValue(businessData.getNewUsers());
            }
            //获得输出流 将Excel写出到浏览器
            ServletOutputStream out = response.getOutputStream();
            excel.write(out);
            //关闭数据
            in.close();
            excel.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        //还有明细数据的获取订单精确到某一天 日期 营业额 有效订单 订单完成率 平均客单价 新增用户数
        //先获取每一天的集合

        //注意是30天所以我们一天一天加入就好了对于每一天查询businessDataVO

    }
}
